package net.yx.service;

import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import io.minio.policy.PolicyType;
import lombok.extern.log4j.Log4j2;
import net.yx.utils.Tools;

import javax.annotation.PostConstruct;
import java.io.InputStream;

/**
 * 描述：
 *
 * @Author shf
 * @Date 2019/5/7 21:59
 * @Version V1.0
 **/
@Log4j2
public class MinIoService {

    private MinioClient minioClient;

    private String endpoint;
    private String accessKey;
    private String secretKey;
    private String bucketName;

    public MinIoService(String endpoint, String accessKey, String secretKey, String bucketName) {
        this.endpoint = endpoint;
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.bucketName = bucketName;
    }

    @PostConstruct
    public void init() {
        try {
            minioClient = new MinioClient(endpoint, accessKey, secretKey);
        } catch (InvalidEndpointException e) {
            e.printStackTrace();
        } catch (InvalidPortException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     *
     * @param stream
     * @param path
     * @param filename
     * @param contentType
     * @return
     */
    public String upload(InputStream stream, String path, String filename, String contentType) {
        String s = null;
        try {
            //存入bucket不存在则创建，并设置为只读
            if (!minioClient.bucketExists(bucketName)) {
                minioClient.makeBucket(bucketName);
                minioClient.setBucketPolicy(bucketName, "*.*", PolicyType.READ_WRITE);
            }

            //文件存储的目录结构
            String objectName = Tools.trimPath(path) + filename;
            minioClient.putObject(bucketName, objectName, stream, contentType);
            log.info("文件上传成功!");
            s = endpoint + "/" + bucketName + "/" + objectName;
        } catch (Exception e) {
            log.error("上传发生错误！", e);
        }
        return s;
    }

    /**
     * 删除文件
     *
     * @return
     */
    public boolean delete(String path, String filename) {
        try {

            minioClient.removeObject(bucketName, path + "/" + filename);
            return true;
        } catch (Exception e) {
            log.error("删除失败！", e.getMessage());
        }
        return false;
    }

    public InputStream download(String path, String filename) {

        try {
            InputStream object = minioClient.getObject(bucketName, path + "/" + filename);
            return object;
        } catch (Exception e) {
            log.error("导出失败！", e);
        }
        return null;
    }
}
